package com.wmh.baseservice.common.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;



@Configuration
public class PathUtil {

    /**
     * 代理访问路径前缀
     */
    public static final String BASE_PATH = "/files/sycm_file/";

    /**
     * 图像代理域名
     * */
    public static final String IMG_URL_PREFIX = "https://www.tdtye.com/";


    @Value("${fileUpload.path}")
    private String path;
    @Value("${fileUpload.type}")
    private Integer type;
    @Value("${spring.profiles.active}")
    private String env;

    public static String staticPath;
    public static Integer staticType;
    public static String staticEnv;

    @PostConstruct
    private void getStatic(){
        staticPath=path;
        staticType=type;
        staticEnv=env;
    }



    /**
     * 获取文件上传绝对路径
     */
    public static String getFullRealPath() {
        if (staticType == 1) {
            return System.getProperty("catalina.home") + "/webapps/";
        } else {
            return staticPath;
        }

    }

    /**
     * 获取文件上传绝对路径
     *
     * @param request
     * @return
     */
    public static String getFullRealPath(HttpServletRequest request) {
        String path = request.getSession().getServletContext().getRealPath("");
        if ("".equals(request.getContextPath())) {
            path = path.replace("ROOT", "");
        } else {
            path = path.replace(request.getContextPath().replace("/", ""), "");
        }
        return path;
    }

    /**
     * 获取域名(http://xx.xx.xx)
     *
     * @param request
     * @return
     */
    public static String getDomain(HttpServletRequest request) {
        String head = request.getRequestURL().toString().startsWith("https") ? "https://" : "http://";
        String port = (request.getServerPort() == 80 || request.getServerPort() == 443) ? "" : (":" + request.getServerPort());
        return head + request.getServerName() + port;
    }

    /**
     * 获取域名+项目名称(http://xx.xx.xx/xx)
     *
     * @param request
     * @return
     */
    public static String getFileUrl(HttpServletRequest request) {
        String head = request.getRequestURL().toString().startsWith("https") ? "https://" : "http://";
        String port = (request.getServerPort() == 80 || request.getServerPort() == 443) ? "" : (":" + request.getServerPort());
        return head + request.getServerName() + port + request.getRequestURI();
    }

    /**
     * 如果即将保存的图像资源路径中包含域名则删除域名 并 返回
     * */
    public static String subImgPathPrefix(String content){
        if (content.contains(IMG_URL_PREFIX)) {
            content = content.replace(IMG_URL_PREFIX,"");
        }
        return content;
    }

}
